package com.example.shop.modules.manage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.shop.modules.manage.service.IUserAdminService;
import com.example.shop.persistence.entity.User;
import com.example.shop.utils.JSONResult;
import com.example.shop.utils.MPPageFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author jason
 * @since 2019-12-17
 */
@Api(tags = "后台接口用户管理")
@RestController
@RequestMapping("/manage/user")
public class UserAdminController {
    @Autowired
    private IUserAdminService userService;

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public JSONResult insertUser(User user){
        return JSONResult.renderSuccess(userService.save(user));
    }

    @ApiOperation(value = "修改用户信息")
    @PostMapping("/update")
    public JSONResult updateUser(User user){
        return JSONResult.renderSuccess(userService.updateById(user));
    }

    @ApiOperation(value = "删除用户")
    @GetMapping("/delete")
    public JSONResult deleteUser(Integer id){
        return JSONResult.renderSuccess(userService.removeById(id));
    }

    @ApiOperation(value = "用户列表", notes = "分页查询")
    @ApiImplicitParam(name="grade",value="用户等级： 1管理员 2普通用户")
    @GetMapping("/list")
    public JSONResult getUserList(Integer page, Integer pageSize, Integer grade){
        Page<User> pages = MPPageFactory.createPage(page,pageSize);
        QueryWrapper ew = new QueryWrapper();
        ew.eq("grade", grade);
        IPage<User> list;
        if(grade == null){
            list = userService.page(pages);
        }else{
            list = userService.page(pages,ew);
        }
        return JSONResult.renderSuccess(list);
    }

    @ApiOperation(value = "用户登录",notes = "用户名、密码必填。登录成功返回用户信息 ")
    @PostMapping("/login")
    public JSONResult loginUser(String username, String password){
        return userService.loginUser(username, password);
    }

    @ApiOperation(value = "查询用户信息")
    @GetMapping("/{id}")
    public JSONResult getUserInfo(Integer id){
        return JSONResult.renderSuccess(userService.getById(id));
    }

}

